package de.dhbw.minf12.mas;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.junit.Before;
import org.junit.Test;

import de.dhbw.minf12.mas.TestInstance.TestInstance;
import de.dhbw.minf12.mas.excel_export.DetailedExcelExporter;
import de.dhbw.minf12.mas.excel_export.ResultExcelExporter;
import de.dhbw.minf12.mas.logic.AbstractTargetFunctionLogic;
import de.dhbw.minf12.mas.logic.ProducerLogic;
import de.dhbw.minf12.mas.logic.SupplierLogic;
import de.dhbw.minf12.mas.mediator.ApprovalMediator;
import de.dhbw.minf12.mas.voter.ApprovalVoter;

public class ApprovalMediatorTester {
	private static int NUMBER_ROUNDS = 10;

	private List<ApprovalVoter> agents;
	private TestInstance instance;
	private ResultExcelExporter resultExporter;
	private DetailedExcelExporter detailExporter;
	
	@Before
	public void setUp() throws Exception {
		instance = new TestInstance();
		agents = new ArrayList<ApprovalVoter>();
		resultExporter = new ResultExcelExporter("Approval");
		detailExporter = new DetailedExcelExporter();
	}
	
	/**
	 * Der Test gibt eine csv Tabelle aus. Diese hab ich in ein Excel Dokument
	 * eingefügt und Diagramme gezeichnet, um zu sehen, ob der Funktionswert
	 * kleiner wird.
	 */
	@Test
	public void test() {
		List<int[][]> instanceList = instance.getNext();

		while(instanceList.size() == 2){
			agents.clear();
			AbstractTargetFunctionLogic targetFunction1 = new SupplierLogic(instanceList.get(0));
			agents.add(new ApprovalVoter(targetFunction1));
			AbstractTargetFunctionLogic targetFunction2 = new ProducerLogic(instanceList.get(1));
			agents.add(new ApprovalVoter(targetFunction2));

			String[] filenames = instance.getFilenames();
			detailExporter.createNewSheet("Approval " + filenames[0] + "-" + filenames[1]);
			
			int solValue1 = 0;
			int solValue2 = 0;
			
			for (int i = 0; i < NUMBER_ROUNDS; i++) {
				ApprovalMediator mediator = new ApprovalMediator(agents, 100000, 30, detailExporter);
				Permutation perm = mediator.startMediation();

				solValue1 += targetFunction1.calculateSolutionValue(perm);
				solValue2 += targetFunction2.calculateSolutionValue(perm);
			}
			resultExporter.addRow(filenames[0], filenames[1], solValue1/NUMBER_ROUNDS, solValue2/NUMBER_ROUNDS,
					(solValue1 + solValue2)/NUMBER_ROUNDS);
			System.out.println("" + filenames[0] + "-" + filenames[1]);
			instanceList = instance.getNext();
		}
		
		try {
			resultExporter.write();
			detailExporter.write();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		instance.close();
		
	}

}
